import {resetRouter} from '@/router'

export const useUserStore = defineStore('user', () => {
    const state = reactive({
        accessToken: getCookieAccessToken(), // 获取token
        refreshToken: '', // 刷新token
        userId: getCookieUserId(), // 用户id
        userName: '', // 用户名称,
        dept: '', // 部门名称
        avatar: '', // 用户头像
        introduction: '',
        unitId: '' //单位id
    })
    const setStoreAccessToken = (accessToken) => {
        state.accessToken = accessToken
        setCookieAccessToken(accessToken)// 将accessToken写cookie
    }
    const setStoreRefreshTokenToken = (refreshToken) => {
        state.refreshToken = refreshToken
        setCookieRefreshToken(refreshToken)
    }
    const setStoreUserId = (userId) => {
        state.userId = userId
        setCookieUserId(userId)
    }
    /**
     * 登录
     * @param url
     * @param params
     * @returns {Promise<unknown>}
     */
    const login = (url, params) => {
        return new Promise(resolve => {
            request({
                url,
                method: 'get',
                params
            }).then(res => {
                if (res.code === 200) {
                    const {userid, accessToken, refreshToken} = res.data
                    setStoreUserId(userid)
                    setStoreAccessToken(accessToken)
                    setStoreRefreshTokenToken(refreshToken)
                    resolve(true)
                } else {
                    resolve(false)
                    requestError(res)
                }
            }).catch(error => {
                resolve(false)
                Emessage('error', error)
            })

            /* const {userid} = params
             setStoreUserId(userid)
             setStoreAccessToken(userid)
             setStoreRefreshTokenToken(userid)
             resolve(true)*/
        })
    }
    const tagsViewStore = useTagsViewStore()
    const resetUserStore = () => {
        state.accessToken = ''
        state.refreshToken = ''
        state.userId = ''
        state.userName = ''
        removeCookieUserId()
        removeCookieToken()
        resetRouter()
        tagsViewStore.delAllViews()
    }
    // 退出系统
    const logout = () => {
        return new Promise(resolve => {
            request({
                url: '/logout',
                method: 'get',
                params: {token: state.accessToken}
            }).then(() => {
                resetUserStore()
                resolve(true)
            })


            /* resetUserStore()
             resolve(true)*/
        })
    }
    const out = () => {
        return new Promise((resolve) => {
            resetUserStore()
            resolve(true)
        })
    }
    return {
        setStoreUserId,
        setStoreAccessToken,
        setStoreRefreshTokenToken,
        resetUserStore,
        login,
        logout,
        out,
        ...toRefs(state)
    }
})
